package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private com.sky.mapper.ReportMapper reportMapper;

    @Autowired
    private com.sky.mapper.UserMapper userMapper;


    @Autowired
    private com.sky.mapper.OrderMapper orderMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /*
     * 营业额统计
     * */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<Double> turnoverList = new ArrayList<>();
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        for (LocalDate date : dateList) {
            LocalDateTime b = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime e = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap();
            map.put("begin", b);
            map.put("end", e);
            map.put("status", 5);

            //获取某个日期的营业额
            Double turnover = reportMapper.sumByMap(map);
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();


        return turnoverReportVO;
    }

    /*
     * 用户数量统计
     * */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        for (LocalDate date : dateList) {
            LocalDateTime b = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime e = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("end", e);
            //总的话只需要添加end
            totalUserList.add(userMapper.countUserByMap(map));
            //新的话要添加begin
            map.put("begin", b);
            newUserList.add(userMapper.countUserByMap(map));
        }
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .build();
        return userReportVO;
    }

    /*
     * 订单数量统计
     * */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {

        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();

        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }


        for (LocalDate date : dateList) {
            //查询每天的订单总数
            LocalDateTime b = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime e = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", b);
            map.put("end", e);
            orderCountList.add(orderMapper.countByMap(map));

            //查询每天的有效订单总数
            map.put("status", 5);
            validOrderCountList.add(orderMapper.countByMap(map));
        }

        //获取总订单数
        Integer total = orderCountList.stream().reduce(Integer::sum).get();
        //获取有效订单数
        Integer valid = validOrderCountList.stream().reduce(Integer::sum).get();

        Double orderCompletionRate = total.doubleValue() / valid.doubleValue();

        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(total)
                .validOrderCount(valid)

                .build();
        return orderReportVO;
    }

    /*
     * 销量前十统计
     * */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {

        LocalDateTime b = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime e = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(b, e);

        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ",");
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ",");
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();


        return salesTop10ReportVO;
    }

    /*
    导出营业数据
    * */
    public void exportBusinessData(HttpServletResponse response) throws FileNotFoundException {

        //1.查询数据库,获取营业数据

        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        //概览数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));


        //2.通过POI 将数据写到Excel文件中

        InputStream in = new FileInputStream("D:\\itcast\\sky\\资料(1)\\资料\\day01\\后端初始工程\\sky-take-out\\sky-server\\src\\main\\resources\\template\\businessdata.xlsx");
        try {
            //基于模版文件创建excel文件
            XSSFWorkbook excel = new XSSFWorkbook(in);

            //填充数据--概览数据
            excel.getSheetAt(0).getRow(1).getCell(1).setCellValue("时间:" + dateBegin + "至" + dateEnd);
            excel.getSheetAt(0).getRow(3).getCell(2).setCellValue( businessData.getTurnover());
            excel.getSheetAt(0).getRow(4).getCell(4).setCellValue( businessData.getUnitPrice());
            excel.getSheetAt(0).getRow(3).getCell(6).setCellValue( businessData.getNewUsers());
            excel.getSheetAt(0).getRow(4).getCell(2).setCellValue( businessData.getValidOrderCount());
            excel.getSheetAt(0).getRow(3).getCell(4).setCellValue( businessData.getOrderCompletionRate());

            //填充数据--明细数据
            for (int i = 0; i <30; i++) {
                LocalDate date = dateBegin.plusDays(i);
                //填充莫一天的营业数据
                BusinessDataVO data = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                excel.getSheetAt(0).getRow(7+i).getCell(1).setCellValue(date.toString());
                excel.getSheetAt(0).getRow(7+i).getCell(2).setCellValue(data.getTurnover());
                excel.getSheetAt(0).getRow(7+i).getCell(3).setCellValue(data.getValidOrderCount());
                excel.getSheetAt(0).getRow(7+i).getCell(4).setCellValue(data.getOrderCompletionRate());
                excel.getSheetAt(0).getRow(7+i).getCell(5).setCellValue(data.getUnitPrice());
                excel.getSheetAt(0).getRow(7+i).getCell(6).setCellValue(data.getNewUsers());


            }

            //3.通过输出流将文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //4.关闭流
            out.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
